<template>
	<div class="doctor-management">
		<!-- 面包屑导航 -->
		<el-breadcrumb separator="/">
			<el-breadcrumb-item>首页</el-breadcrumb-item>
			<el-breadcrumb-item>医生信息管理</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 增加 -->
		<div class="add-btn-container">
			<el-button type="primary" icon="el-icon-circle-plus" @click="openAddDialog" size="medium">
				添加医生信息
			</el-button>
		</div>
		<!-- 添加对话框 -->
		<el-dialog title="添加医生信息" :visible.sync="addDialogVisible" width="50%" :before-close="handleAddDialogClose">
			<el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
				<!-- 医生姓名 -->
				<el-form-item label="医生姓名" prop="name">
					<el-input v-model="addForm.name"></el-input>
				</el-form-item>

				<!-- 年龄 -->
				<el-form-item label="年龄" prop="age">
					<el-input v-model="addForm.age" type="number"></el-input>
				</el-form-item>

				<!-- 性别 -->
				<el-form-item label="性别" prop="sex">
					<el-radio-group v-model="addForm.sex">
						<el-radio label="1">男</el-radio>
						<el-radio label="2">女</el-radio>
					</el-radio-group>
				</el-form-item>

				<!-- 级别 -->
				<el-form-item label="级别" prop="levelId">
					<el-select v-model="addForm.levelId" placeholder="请选择级别">
						<el-option v-for="level in levelList" :key="level.id" :label="`${level.id} - ${level.name}`"
							:value="level.id"></el-option>
					</el-select>
				</el-form-item>

				<!-- 手机号 -->
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="addForm.phone"></el-input>
				</el-form-item>

				<!-- 诊治类别 -->
				<el-form-item label="诊治类别" prop="typeId">
					<el-select v-model="addForm.typeId" placeholder="请选择诊治类别">
						<el-option v-for="type in treatmentTypeList" :key="type.id" :label="`${type.id} - ${type.name}`"
							:value="type.id"></el-option>
					</el-select>
				</el-form-item>
			</el-form>

			<!-- 对话框底部操作按钮 -->
			<div slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAddSave">保存</el-button>
			</div>
		</el-dialog>
		<!-- 搜索框 -->
		<el-input placeholder="查询（输入要查询的医生姓名）" v-model="searchKeyword" class="search-input"
			@input="handleSearch"></el-input>
		<!-- 医生信息列表 -->
		<el-table :data="filteredDoctorList" stripe style="width: 100%" v-loading="loading">
			<el-table-column prop="name" label="医生姓名"></el-table-column>
			<el-table-column prop="age" label="年龄" sortable></el-table-column>
			<el-table-column prop="sex" label="性别" sortable>

			</el-table-column>
			<el-table-column prop="level" label="级别" sortable></el-table-column>
			<el-table-column prop="phone" label="手机号"></el-table-column>
			<el-table-column prop="treatmentType" label="诊治类别" sortable></el-table-column>
			<el-table-column label="操作" width="150">
				<template slot-scope="scope">
					<el-button type="text" icon="el-icon-document"
						@click="openPasswordDialog(scope.row.id)">修改密码</el-button>
					<el-button type="text" icon="el-icon-edit" @click="editDoctor(scope.row)">编辑</el-button>
					<el-button type="text" icon="el-icon-delete" @click="delDoctor(scope.row.id)"
						style="color: #F56C6C;">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 密码修改对话框 -->
		<el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="350px" :before-close="closePasswordDialog">
			<el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
				<el-form-item label="新密码" prop="password">
					<el-input v-model="passwordForm.password" type="password" show-password
						placeholder="请输入新密码"></el-input>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="passwordDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="savePassword">确认修改</el-button>
			</div>
		</el-dialog>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑医生信息" :visible.sync="editDialogVisible" width="50%" :before-close="handleEditDialogClose">
			<el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
				<!-- 医生编号（只读） -->
				<el-form-item label="医生编号" prop="id">
					<el-input v-model="editForm.id" disabled></el-input>
				</el-form-item>

				<!-- 医生姓名 -->
				<el-form-item label="医生姓名" prop="name">
					<el-input v-model="editForm.name"></el-input>
				</el-form-item>

				<!-- 年龄 -->
				<el-form-item label="年龄" prop="age">
					<el-input v-model="editForm.age"></el-input>
				</el-form-item>

				<!-- 性别 -->
				<el-form-item label="性别" prop="sex">
					<el-radio-group v-model="editForm.sex">
						<el-radio label="1">男</el-radio>
						<el-radio label="2">女</el-radio>
					</el-radio-group>
				</el-form-item>

				<!-- 级别 -->
				<el-form-item label="级别" prop="levelId">
					<el-select v-model="editForm.levelId" placeholder="请选择级别">
						<el-option v-for="level in levelList" :key="level.id" :label="`${level.id} - ${level.name}`"
							:value="level.id"></el-option>
					</el-select>
				</el-form-item>

				<!-- 手机号 -->
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="editForm.phone"></el-input>
				</el-form-item>

				<!-- 诊治类别 -->
				<el-form-item label="诊治类别" prop="TypeId">
					<el-select v-model="editForm.typeId" placeholder="请选择诊治类别">
						<el-option v-for="type in treatmentTypeList" :key="type.id" :label="`${type.id} - ${type.name}`"
							:value="type.id"></el-option>
					</el-select>
				</el-form-item>
			</el-form>

			<!-- 对话框底部操作按钮 -->
			<div slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleEditSave">保存</el-button>
			</div>
		</el-dialog>
		<!-- 分页 -->
		<div class="pagination">
			<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
				:current-page="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next, jumper"
				:disabled="loading"></el-pagination>
		</div>
	</div>
</template>

<script>
	import api from '@/api'; // 导入封装的API模块

	export default {
		data() {
			return {
				doctorList: [], // 原始数据
				filteredDoctorList: [], // 过滤后的数据（用于展示）
				currentPage: 1,
				pageSize: 10,
				total: 0,
				searchKeyword: '',
				loading: false,
				searchTimer: null, // 搜索防抖计时器
				editDialogVisible: false, // 编辑对话框显示控制
				editForm: {}, // 编辑表单数据（初始为空对象）
				editRules: { // 表单验证规则
					name: [{
						required: true,
						message: '请输入医生姓名',
						trigger: 'blur'
					}],
					age: [{
						required: true,
						message: '请输入年龄',
						trigger: 'blur'
					}, ],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: 'change'
					}],
					levelId: [{
						required: true,
						message: '请选择级别',
						trigger: 'change'
					}],
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 15,
							message: '手机号格式不正确',
							trigger: 'blur'
						}
					],
					typeId: [{
						required: true,
						message: '请选择诊治类别',
						trigger: 'change'
					}],
				},
				addDialogVisible: false, // 添加对话框显示控制
				addForm: { // 添加表单数据
					name: '',
					age: null,
					sex: null,
					levelId: null,
					phone: '',
					typeId: null
				},
				addRules: { // 添加表单验证规则
					name: [{
						required: true,
						message: '请输入医生姓名',
						trigger: 'blur'
					}],
					age: [{
						required: true,
						message: '请输入年龄',
						trigger: 'blur'
					}, ],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: 'change'
					}],
					levelId: [{
						required: true,
						message: '请选择级别',
						trigger: 'change'
					}],
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 15,
							message: '手机号格式不正确',
							trigger: 'blur'
						}
					],
					typeId: [{
						required: true,
						message: '请选择诊治类别',
						trigger: 'change'
					}]
				},
				levelList: [], // 级别列表
				treatmentTypeList: [], // 诊治类别列表
				passwordDialogVisible: false,
				passwordForm: {
					doctorId: null, // 医生ID
					password: '' // 新密码
				},
				passwordRules: {
					password: [{
						required: true,
						message: '请输入新密码',
						trigger: 'blur'
					}, ]
				}
			};
		},

		mounted() {
			this.fetchDoctorList();
			this.fetchLevelList();
			this.fetchTreatmentTypeList();
		},

		methods: {
			// 搜索处理（带防抖）
			handleSearch() {
				// 清除之前的计时器
				if (this.searchTimer) clearTimeout(this.searchTimer);

				// 设置新的计时器（300ms防抖）
				this.searchTimer = setTimeout(() => {
					if (!this.searchKeyword.trim()) {
						this.filteredDoctorList = [...this.doctorList];
						return;
					}

					const keyword = this.searchKeyword.toLowerCase();
					this.filteredDoctorList = this.doctorList.filter(item =>
						item.name && item.name.toLowerCase().includes(keyword)
					);
				}, 300);
			},

			// 获取医生信息数据
			async fetchDoctorList() {
			    this.loading = true;
			    try {
			        const data = {
			            currentPage: this.currentPage,
			            pageSize: this.pageSize,
			            name: this.searchKeyword  // 传递搜索关键词到后端
			        };
			
			        const response = await api.doctor.getAllDoctors(data);
			
			        if (response.code === 0) {
			            // 假设后端返回的data结构为 { list: [...], total: 100 }
			            this.doctorList = response.data.list || [];
			            this.filteredDoctorList = [...this.doctorList];
			            this.total = response.data.total; // 从后端获取总记录数
			        } else {
			            this.$message.error(response.message || '获取数据失败');
			        }
			    } catch (error) {
			        console.error('请求出错:', error);
			        this.$message.error('数据加载失败，请稍后重试');
			    } finally {
			        this.loading = false;
			    }
			},

			async fetchLevelList() {
				try {
					const response = await api.doctor.getAllDoctorLevels();
					if (response.code === 0) {
						this.levelList = response.data || [];
					} else {
						this.$message.error(response.message || '获取级别列表失败');
					}
				} catch (error) {
					console.error('获取级别列表出错:', error);
					this.$message.error('获取级别列表失败，请稍后重试');
				}
			},

			// 获取诊治类别列表
			async fetchTreatmentTypeList() {
				try {
					const response = await api.doctor.getAllDoctorTypes();
					if (response.code === 0) {
						this.treatmentTypeList = response.data || [];
					} else {
						this.$message.error(response.message || '获取诊治类别列表失败');
					}
				} catch (error) {
					console.error('获取诊治类别列表出错:', error);
					this.$message.error('获取诊治类别列表失败，请稍后重试');
				}
			},

			// 分页变化
			handleCurrentChange(page) {
				this.currentPage = page;
				this.fetchDoctorList();
			},
			handleSizeChange(size) {
				this.pageSize = size;
				this.currentPage = 1; // 重置为第一页
				this.fetchDoctorList();
			},

			// 编辑医生信息
			editDoctor(row) {
				// 深拷贝当前行数据（避免直接修改原数据）
				this.editForm = JSON.parse(JSON.stringify(row));
				this.editDialogVisible = true;
			},

			// 关闭编辑对话框前重置表单状态
			handleEditDialogClose() {
				this.$refs.editFormRef && this.$refs.editFormRef.resetFields();
				this.editForm = {};
			},

			// 保存编辑内容（调用更新接口）
			async handleEditSave() {
				// 先校验表单
				const isValid = await new Promise(resolve => {
					this.$refs.editFormRef.validate(valid => resolve(valid));
				});
				if (!isValid) return;

				try {
					this.loading = true;
					// 调用更新接口（假设 api.doctor.update 对应后端 /doctor/update 接口）
					const response = await api.doctor.update(this.editForm);

					if (response.code === 0) {
						this.$message.success('修改成功');
						this.editDialogVisible = false; // 关闭对话框
						this.fetchDoctorList(); // 刷新数据列表
					} else {
						this.$message.error(response.message || '修改失败');
					}
				} catch (error) {
					console.error('修改请求出错:', error);
					this.$message.error('修改失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},

			// 打开添加对话框
			openAddDialog() {
				this.addDialogVisible = true;
				this.addForm = {
					name: '',
					age: null,
					sex: null,
					levelId: null,
					phone: '',
					typeId: null
				}; // 清空表单
			},

			// 关闭添加对话框前重置表单状态
			handleAddDialogClose() {
				this.$refs.addFormRef && this.$refs.addFormRef.resetFields();
				this.addForm = {
					name: '',
					age: null,
					sex: null,
					levelId: null,
					phone: '',
					treatmentTypeId: null
				};
			},

			// 保存新增医生信息（调用添加接口）
			async handleAddSave() {
				// 校验表单
				const isValid = await new Promise(resolve => {
					this.$refs.addFormRef.validate(valid => resolve(valid));
				});
				if (!isValid) return;

				try {
					this.loading = true;
					// 调用添加接口（api.doctor.add 对应后端 /doctor/add）
					const response = await api.doctor.add(this.addForm);

					if (response.code === 0) {
						this.$message.success('添加成功');
						this.addDialogVisible = false; // 关闭对话框
						this.fetchDoctorList(); // 刷新数据列表（新增后自动刷新）
					} else {
						this.$message.error(response.message || '添加失败');
					}
				} catch (error) {
					console.error('添加请求出错:', error);
					this.$message.error('添加失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},

			// 删除医生信息
			async delDoctor(id) {
				try {
					// 显示确认对话框
					await this.$confirm('确定要删除这个医生信息吗？', '删除确认', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					});

					this.loading = true;

					// 调用删除API
					const response = await api.doctor.delete({
						id
					});

					if (response.code === 0) {
						this.$message.success('删除成功');
						// 重新加载数据（如果当前页只剩一条，返回上一页）
						if (this.doctorList.length === 1 && this.currentPage > 1) {
							this.currentPage -= 1;
						}
						this.fetchDoctorList();
					} else {
						this.$message.error(response.message || '删除失败');
					}
				} catch (error) {
					// 用户取消删除时不做处理
					if (error !== 'cancel') {
						console.error('删除失败:', error);
						this.$message.error('删除失败，请稍后重试');
					}
				} finally {
					this.loading = false;
				}
			},
			openPasswordDialog(doctorId) {
				this.passwordDialogVisible = true;
				this.passwordForm = {
					doctorId,
					password: ''
				}; // 初始化表单数据
			},

			// 关闭对话框时重置表单
			closePasswordDialog() {
				this.$refs.passwordForm.resetFields();
				this.passwordForm.password = '';
			},

			// 保存密码修改
			async savePassword() {
				// 表单验证
				const isValid = await this.$refs.passwordForm.validate();
				if (!isValid) return;

				try {
					// 调用后端接口（假设接口需要 { id, password } 参数）
					const response = await api.doctor.updatePassword({
						id: this.passwordForm.doctorId,
						password: this.passwordForm.password
					});

					if (response.code === 0) {
						this.$message.success('密码修改成功');
						this.passwordDialogVisible = false;
					} else {
						this.$message.error(response.message || '修改失败');
					}
				} catch (error) {
					console.error('密码修改失败:', error);
					this.$message.error('网络错误，请稍后重试');
				}
			}
		}
	};
</script>

<style lang="less" scoped>
	.doctor-management {
		padding: 20px;

		.search-input {
			margin-bottom: 15px;
		}

		.el-table {
			margin-bottom: 15px;
		}

		.pagination {
			text-align: center;
		}

		.add-btn-container {
			margin: 15px 0;
			display: flex;
			/* 使用 Flex 布局 */
			justify-content: flex-end;
			/* 按钮靠右 */

			.el-button {
				padding: 10px 20px;
				/* 增大内边距 */
				font-size: 14px;
				/* 调整字体大小 */
			}
		}
	}
</style>